// 权限检查工具类
import request from '@/utils/request'

export default class PermissionUtil {
  
  // 检查用户是否拥有指定权限
  static hasPermission(permissionCode) {
    const userPermissions = JSON.parse(localStorage.getItem('userPermissions') || '[]')
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const isSuperAdmin = (userInfo?.id === 1) || (Array.isArray(userInfo?.roles) && userInfo.roles.some(r => r.roleCode === 'SYSTEM_ADMIN'))
    if (isSuperAdmin || userPermissions.includes('admin:all')) return true
    return userPermissions.includes(permissionCode)
  }
  
  // 检查用户是否拥有任意一个权限
  static hasAnyPermission(permissionCodes) {
    const userPermissions = JSON.parse(localStorage.getItem('userPermissions') || '[]')
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const isSuperAdmin = (userInfo?.id === 1) || (Array.isArray(userInfo?.roles) && userInfo.roles.some(r => r.roleCode === 'SYSTEM_ADMIN'))
    if (isSuperAdmin || userPermissions.includes('admin:all')) return true
    return permissionCodes.some(code => userPermissions.includes(code))
  }
  
  // 检查用户是否拥有所有指定权限
  static hasAllPermissions(permissionCodes) {
    const userPermissions = JSON.parse(localStorage.getItem('userPermissions') || '[]')
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const isSuperAdmin = (userInfo?.id === 1) || (Array.isArray(userInfo?.roles) && userInfo.roles.some(r => r.roleCode === 'SYSTEM_ADMIN'))
    if (isSuperAdmin || userPermissions.includes('admin:all')) return true
    return permissionCodes.every(code => userPermissions.includes(code))
  }
  
  // 获取当前用户权限列表
  static getCurrentPermissions() {
    return JSON.parse(localStorage.getItem('userPermissions') || '[]')
  }

  // 从服务端同步当前用户与权限，成功则写入本地
  static async syncFromServer() {
    const token = localStorage.getItem('token')
    if (!token) {
      localStorage.removeItem('userInfo')
      localStorage.setItem('userPermissions', JSON.stringify([]))
      return { ok: false }
    }
    try {
      const res = await request.get('/auth/info')
      const data = res.data?.data || {}
      let user = data.user || {}
      // 追加拉取用户角色信息，便于前端识别 SYSTEM_ADMIN 等
      if (user && user.id) {
        try {
          const rolesResp = await request.get(`/roles/user/${user.id}`)
          const roles = Array.isArray(rolesResp?.data?.data) ? rolesResp.data.data : []
          user = { ...user, roles }
        } catch (_) {
          // 忽略角色拉取错误，保持已有信息
        }
      }
      if (user) {
        localStorage.setItem('userInfo', JSON.stringify(user))
      }
      const perms = Array.isArray(data.permissions) ? data.permissions : []
      localStorage.setItem('userPermissions', JSON.stringify(perms))
      return { ok: true, permissions: perms, user }
    } catch (e) {
      // 不抛错，保持现状
      return { ok: false, error: e }
    }
  }
  
  // 检查用户是否拥有指定角色
  static hasRole(roleCode) {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    return userInfo.roles && userInfo.roles.some(role => role.roleCode === roleCode)
  }
  
  // 检查用户是否拥有任意一个角色
  static hasAnyRole(roleCodes) {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.roles) return false
    return roleCodes.some(code => userInfo.roles.some(role => role.roleCode === code))
  }

  // 检查是否为超级管理员
  static isSuperAdmin() {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const userPermissions = JSON.parse(localStorage.getItem('userPermissions') || '[]')
    return (userInfo?.id === 1) || 
           (Array.isArray(userInfo?.roles) && userInfo.roles.some(r => r.roleCode === 'SYSTEM_ADMIN')) ||
           userPermissions.includes('admin:all')
  }

  // 检查是否为普通管理员（有后台访问权限但不是超级管理员）
  static isNormalAdmin() {
    const userPermissions = JSON.parse(localStorage.getItem('userPermissions') || '[]')
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const hasUserSearch = userPermissions.includes('user:search')
    const isOperationAdmin = Array.isArray(userInfo?.roles) && userInfo.roles.some(r => r.roleCode === 'OPERATION_ADMIN')
    return (hasUserSearch || isOperationAdmin) && !this.isSuperAdmin()
  }

  // 检查是否可以访问用户管理相关页面（仅超级管理员）
  static canAccessUserManagement() {
    return this.isSuperAdmin()
  }

  // 检查是否可以访问角色权限管理页面（仅超级管理员）
  static canAccessRoleManagement() {
    return this.isSuperAdmin()
  }
}